"use strict"

/**
 * 邮件发送接口
 *  
 */

/**
 * 将邮件转发用户信息插入数据库 mailconfig 表中
 * insert into mailconfig(host, secureConnection, fromaddr, username, userpass, subject, port) values
 * ('mail.xxxx.com', 1, '招标信息反馈<xx@xxxx.com>', 'xx@xxxx.com', 'password', '[重要] 新的招标信息动态', 25);
 */

var nodemailer = require('nodemailer');
var q = require("q");
var db = require("../db");

// var https = require('https');
// https.globalAgent.options.secureProtocol = 'SSLv3_method';

var buildConfig = function () {
    var def = q.defer();
    try {
        db.query("select * from mailconfig limit 1", function (err, items) {
            if (err || items.length == 0) {
                def.resolve(null);
            } else {
                var item = items[0];
                var config = {};
                config.secureConnection = item["secureConnection"] == 1;
                config.host = item["host"];
                config.from = item["fromaddr"];
                config.port = item["port"];
                var auth = {};
                auth.user = item["username"];
                auth.pass = item["userpass"];
                config.subject = item["subject"];
                config.auth = auth;
                def.resolve(config);
            }
        });
    } catch (e) {
        process.nextTick(function () {
            def.resolve(null);
        });
    }
    return def.promise;
};

var smtpTransport = null;

var buildSmtpT = function (conf) {
    var def = q.defer();
    process.nextTick(function () {
        smtpTransport = nodemailer.createTransport("SMTP", conf);
        def.resolve(conf);
    });
    return def.promise;
};

var extend = function (src, src2) {
    var result = src;
    for (var k in src2) {
        if (src2.hasOwnProperty(k)) {
            result[k] = src2[k];
        }
    }
    return result;
}

var sendHandler = function (toaddr, text, cb) {
    return function (conf) {
        var mailOptions = {
            subject: conf.subject, // 标题
            text: "各位，明天大家的工作就是写下面的语句100遍： 世界，你好！" // html 内容
        }
        var def = q.defer();
        if (conf) {
            var sendInfo = extend(mailOptions, { 'to': toaddr, 'text': text, 'from': conf.from});
            smtpTransport.sendMail(sendInfo, function (error, response) {
                if (error) {
                    console.log(error);
                    cb(error);
                } else {
                    console.log("Message sent: " + response.message);
                    cb(null, response.message);
                }
                smtpTransport.close(); // 如果没用，关闭连接池
                def.resolve();
            });
        } else {
            process.nextTick(function () {
                console.log("mail config is null");
                def.resolve();
            });
        }
        return def.promise;
    };
};

var exportObject = {
    version: "1.0.0",
    name: "crawler mail support",
    text: "",
    sendMail: function (toaddr, cb) {
        var task = q();
        task.then(buildConfig).then(buildSmtpT).then(sendHandler(toaddr, exportObject.text, cb));
    }
};


exports = module.exports = exportObject;
